<template>
  <div>
    <!-- 面包屑导航区 -->
    <hamburger :secTitle="secTitle" :thirdTitle="thirdTitle"></hamburger>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 警示区域 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable="false" show-icon></el-alert>
      <!-- 商品选择区域 -->
      <el-row class="row_opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            size="medium"
            :props="cascaderProps"
            expandTrigger="hover"
            @change="cateChanged"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="info"
            plain
            :disabled="isBtnDiabled"
            @click="manyDialogVisible = true"
          >添加参数</el-button>
          <el-table border stripe :data="manyCateList">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(item,i) in scope.row.attr_vals"
                  closable
                  @close="handleClose(i,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="small"
                  @click="showEditDialog(scope.row)"
                >编辑</el-button>
                <el-button
                  type="success"
                  icon="el-icon-delete"
                  size="small"
                  @click="removeAttr(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="info"
            plain
            :disabled="isBtnDiabled"
            @click="manyDialogVisible = true"
          >添加属性</el-button>
          <el-table border stripe :data="onlyCateList">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(item,i) in scope.row.attr_vals"
                  closable
                  @close="handleClose(i,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="small"
                  @click="showEditDialog(scope.row)"
                >编辑</el-button>
                <el-button
                  type="success"
                  icon="el-icon-delete"
                  size="small"
                  @click="removeAttr(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加对话框 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="manyDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form label-width="100px" :rules="rules" :model="ruleForm" ref="ruleRef">
        <el-form-item :label="titleText+':'" prop="attr_name">
          <el-input v-model="ruleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="manyDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAttr">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog
      :title="'修改'+titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form label-width="100px" :rules="rules" :model="editRuleForm" ref="editRuleRef">
        <el-form-item :label="titleText+':'" prop="attr_name">
          <el-input v-model="editRuleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editAttr">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      secTitle: '商品管理',
      thirdTitle: '参数列表',
      params: {
        type: '',
        pagenum: '',
        pagesize: ''
      },
      cateList: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      selectedKeys: [],
      activeName: 'many',
      manyCateList: [],
      onlyCateList: [],
      manyDialogVisible: false,
      editDialogVisible: false,
      ruleForm: {
        attr_name: ''
      },
      editRuleForm: {
        attr_name: '',
        attr_vals: '',
        attr_id: ''
      },
      rules: {
        attr_name: [
          { required: true, message: '请添加参数名称', trigger: 'blur' }
        ]
      },
      attrList: {
        attr_name: ''
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.params
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品参数失败')
      } else {
        this.cateList = res.data
      }
    },
    cateChanged() {
      this.getParamsData()
    },
    async getParamsData() {
      //   console.log(this)
      //判断是否选中三级参数
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyCateList = []
        this.onlyCateList = []
        return
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败')
      } else {
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          //添加布尔值控制文本框的显示与隐藏
          item.inputVisible = false
          item.inputValue = ''
        })
        //   console.log(res.data)

        if (this.activeName === 'many') {
          this.manyCateList = res.data
        } else {
          this.onlyCateList = res.data
        }
      }
    },
    handleClick() {
      this.getParamsData()
    },
    addAttr() {
      this.$refs.ruleRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.ruleForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加属性失败')
        } else {
          this.$message.success('添加成功')
          this.getParamsData(), (this.manyDialogVisible = false)
        }
      })
    },
    addDialogClosed() {
      this.$refs.ruleRef.resetFields()
    },
    async showEditDialog(attr) {
      this.editDialogVisible = true
      // console.log(attr)
      const {
        data: res
      } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr.attr_id}`,
        { params: { attr_sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败')
      } else {
        console.log(res.data)
        this.editRuleForm = res.data
        this.getParamsData()
      }
    },
    editDialogClosed() {
      this.$refs.editRuleRef.resetFields()
    },
    editAttr() {
      this.$refs.editRuleRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editRuleForm.attr_id}`,
          {
            attr_name: this.editRuleForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('添加属性失败')
        } else {
          this.$message.success('添加成功')
          this.getParamsData(), (this.editDialogVisible = false)
        }
      })
    },
    async removeAttr(id) {
      // console.log(attr)
      const confirmRes = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmRes !== 'confirm') {
        return this.$message.info('取消删除参数')
      }

      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败')
      } else {
        this.$message.success('删除参数成功')
        this.getParamsData()
      }
    },
    showInput(row) {
      row.inputVisible = true
      //$nextTick方法的作用，就是当页面上的元素被重新渲染之后，才会指定回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async handleInputConfirm(row) {
      //   const inputValue = this.inputValue
      //   console.log(row)
      //   if (inputValue) {
      //     this.dynamicTags.push(inputValue)
      //   }
      //   this.inputVisible = false
      //   this.inputValue = ''
      if (row.inputValue.trim().length == 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      this.saveAttr(row)
    },
    async saveAttr(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('更新参数失败')
      } else {
        this.$message.success('更新参数成功')
      }
    },
    handleClose(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttr(row)
    }
  },
  computed: {
    isBtnDiabled() {
      if (this.selectedKeys.length !== 3) {
        return true
      }
      return false
    },
    cateId() {
      if (this.selectedKeys.length == 3) {
        return this.selectedKeys[2]
      }
      return null
    },
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.row_opt {
  margin: 15px 0;
}
.el-button {
  margin-bottom: 20px;
}
.el-tag,
.button-new-tag,
.input-new-tag {
  margin-left: 10px;
}
.input-new-tag {
  width: 150px;
}
</style>